package lambdasinaction.chap2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import lambdasinaction.chap2.MyFilterApples.Apple;

/**
 * 抽象化
 * 酷不酷？你现在在灵活性和简洁性找到了最佳平衡点，这在 Java8 之前是不可能做到的！
 * @author Fish
 * @since 0.0.1 2018/7/15 18:27
 */
public class AbstractFilter {

  public static void main(String[] args) {
    List<Apple> inventory = Arrays.asList(new Apple("red", 130),
        new Apple("green", 160),
        new Apple("green", 120),
        new Apple("red", 30));
//    List<Apple> redApples = filter(inventory, (Apple a) -> a.getColor().equals("red"));
//    System.out.println(redApples);

    List<Integer> integers = Arrays.asList(1, 10, 30);
    List<Integer> evenIntegers = filter(integers, integer -> integer % 2 == 0);
    System.out.println(evenIntegers);
  }



  public static <T> List<T> filter(List<T> list, Predicate<T> p) {
    List<T> result = new ArrayList<T>();
    for (T t: list) {
      if (p.test(t)) {
        result.add(t);
      }
    }
    return result;
  }

}
